/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-11-27     balanceTWK   first version
 */

#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include <arpa/inet.h> 
#include <netdev.h>
#include <ntp.h>

#include "lora.h"
#include "net.h"



/* defined the ESP8266 reset pin: PB2 */
#define ESP8266_RESET_PIN    GET_PIN(B, 2)

void set_esp8266_enable(void)
{
	rt_pin_mode(ESP8266_RESET_PIN,PIN_MODE_OUTPUT);
	rt_pin_write(ESP8266_RESET_PIN,0);
	rt_thread_mdelay(1000);
	rt_pin_write(ESP8266_RESET_PIN,1);
	//rt_kprintf("esp8266 enable ,PB8 = 1\r\n");
}
INIT_PREV_EXPORT(set_esp8266_enable);




struct netdev *espdev = NULL;
static rt_uint8_t data[32];
int main(void)
{
		espdev = netdev_get_by_name("esp0");
		if(espdev == NULL){
			rt_kprintf("get esp0 dev error!\n");
		}
		
		while(!netdev_is_internet_up(espdev)){
			//rt_kprintf("wait for link up!\n");
			rt_thread_mdelay(100);
		}
		rt_kprintf("esp 0 is link up!\n");
		//rt_thread_mdelay(100);
    char *ip_str = inet_ntoa(espdev->ip_addr);
		rt_kprintf("## ip = %s\n",ip_str);
		
		time_t cur_time;
		cur_time = ntp_get_time(NULL);
		if(cur_time)
			rt_kprintf("NTP Server Time: %s", ctime((const time_t*) &cur_time));
		
		for(int i=0;i<5;i++){
			if(client_socket_init() == RT_EOK) break;
			else rt_thread_mdelay(200);
		}
		
		while (1)
    {
       rt_memset(data,0,sizeof(data));
			lora_get_msg(data);
			
			//cur_time = ntp_get_time(NULL);
			//rt_kprintf("Time: %s", ctime((const time_t*) &cur_time));
			rt_kprintf("\t\t %x,%x :%d: %d %d\n",data[0],data[1],data[2],(data[4]<<8)|data[3],(data[6]<<8)|data[5]);
			client_send_data(data,32);

    }
}
